﻿using CommunityToolkit.Mvvm.ComponentModel;
using System.Xml.Serialization;

namespace CommonTools
{

    /// <summary>
    /// 使用方法：
    /// public class TestClass:ConfigBase<TestClass>
    //    {
    //        public string Name { get; set; } = "ycr40";
    //        public string Description { get; set; } = "test....";
    //    }
    //  注意：有列表类属性时，构造函数不能对列表加入默认初始化条目（序列化时会增加两遍），需要默认初始化，初始化重写_DefaultInit
    //  
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ConfigBase<T>:ObservableObject  where T : class       
    {        
        static T _current = null;

        [XmlIgnore]
        public static T Current { 
            get {

                if (_current == null)
                {
                    try
                    {
                        var type = typeof(T);
                        var path = Path.Combine(Directory.GetCurrentDirectory(), "configs", $"{type.Name}.config");
                        if (File.Exists(path))
                        {
                            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                            {
                                XmlSerializer serializer = new XmlSerializer(type);
                                _current = serializer.Deserialize(fs) as T;
                                fs.Close();
                            }
                        }
                    }
                    catch {

                    }
                    finally
                    {
                        if (_current == null)
                        {
                            _current = Activator.CreateInstance<T>();

                            //初始化
                            (_current as ConfigBase<T>)!._DefaultInit();

                            //保存到文件
                            (_current as ConfigBase<T>)!.Save();
                        }
                    }                   

                    
                }
                return _current; 
            } 
        }

        public void Save()
        {

            var type = typeof(T);
            var dir= Path.Combine(Directory.GetCurrentDirectory(), "configs");
            if(!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var path = Path.Combine(dir, $"{type.Name}.config");
            var obj = Current;
            using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                XmlSerializer serializer = new XmlSerializer(type);
                serializer.Serialize(stream, obj);
                stream.Close();
            }
        }

        protected virtual void _DefaultInit()
        {

        }

    }

}
